package com.curry.apiprovider.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.curry.apiprovider.crawler.Constants;
import com.curry.apiprovider.crawler.PageProcessorFactory;
import com.curry.apiprovider.crawler.pageProcessor.job.*;
import com.curry.apiprovider.generator.mapper.TJobInfoMapper;
import com.curry.apiprovider.util.DateUtils;
import com.curry.apiprovider.util.IDGenerator;
import com.curry.apiprovider.util.StringUtils;
import com.curry.livehelper.entity.domain.TJobInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.util.List;

/**
 * 爬虫服务工具类
 */
@Service
public class CrawlerWrapperService {
    @Autowired
    private PageProcessorFactory pageProcessorFactory;
    private Logger logger = LoggerFactory.getLogger(CrawlerWrapperService.class);
    @Autowired
    private TJobInfoMapper tJobInfoMapper;

    public int getJobTotalPage(String url, String params[]) {
        FirstPageProcessor firstPageProcessor = new FirstPageProcessor(params);
        pageProcessorFactory.setPageProcessor(firstPageProcessor);
        JobPipLine firstJbPipLine = new JobPipLine();
        pageProcessorFactory.setPipeline(firstJbPipLine);
        firstJbPipLine.setKeyType(Constants.KEY_JOB_LIST_PAGE_URL);
        pageProcessorFactory.startSpider(StringUtils.replaceAll(params, Constants.JOB_URL), 4);
        int totalPageSize = Integer.valueOf(firstJbPipLine.getData());
        return totalPageSize;
    }

    @Transactional
    public void startJobCrawler(String url, String params[]) {
        long start_time = System.currentTimeMillis();
        logger.warn("startJobCrawler 开始");
        JobPipLine jobPipLine = new JobPipLine();
        jobPipLine.setKeyType(Constants.KEY_JOB_INFO);
        JobPageProcessor jobPageProcessor = new JobPageProcessor(params);
        pageProcessorFactory.setPageProcessor(jobPageProcessor);
        pageProcessorFactory.setPipeline(jobPipLine);
        pageProcessorFactory.startSpider(StringUtils.replaceAll(params, url), 4);
        String jobTempInfo = readJobTempInfo(Constants.FILE_TEMP_JOB);
        List<TJobInfo> tJobInfos = JSON.parseArray(jobTempInfo, TJobInfo.class);
        for (int i = 0; i < tJobInfos.size(); i++) {
            TJobInfo tJobInfo = tJobInfos.get(i);
            try {
                if (tJobInfo != null) {
                    TJobInfo queryJob = new TJobInfo();
                    queryJob.setCommpanyName(tJobInfo.getCommpanyName());
                    queryJob.setJobPost(tJobInfo.getJobPost());
                    TJobInfo jobInfo = tJobInfoMapper.selectOne(queryJob);
                    if (jobInfo == null) {
                        tJobInfo.setInsertTime(DateUtils.getCurrentDate("yyyyMMddHHmmss"));
                        tJobInfo.setJobId(String.valueOf(IDGenerator.generateUUID()));
                        logger.warn("插入工作 tJobInfos " + tJobInfos.size() + " 插入 " + i);
                        tJobInfoMapper.insert(tJobInfo);
                    } else {
                        //修改发布时间
                        EntityWrapper<TJobInfo> entityWrapper = new EntityWrapper<>(new TJobInfo());
                        TJobInfo updateJob = new TJobInfo();
                        updateJob.setPublishDate(tJobInfo.getPublishDate());
                        entityWrapper.where("commpanyName={0}", tJobInfo.getCommpanyName())
                                .and("jobPost={0}", tJobInfo.getJobPost());
                        tJobInfoMapper.update(updateJob, entityWrapper);
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        long end_time = System.currentTimeMillis();
        logger.warn("startJobCrawler 结束 花费时间 " + (end_time - start_time));
    }

    public static void main(String args[]) {
    }
    private String readJobTempInfo(String filePath) {
        BufferedReader bufferedReader = null;
        try {
            File file = new File(filePath);
            if (file.exists()) {
                FileReader fileReader = new FileReader(file);
                bufferedReader = new BufferedReader(fileReader);
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append(bufferedReader.readLine());
                logger.warn("readJobTempInfo " + stringBuffer.toString());
                if (file.delete()) {
                    logger.warn("删除临时文件成功");
                    return stringBuffer.toString();
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

}
